import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'

export const useAppStore = defineStore('app', {
  state: () => ({
    // 应用基础状态
    loading: false,
    loadingText: '',
    pageLoading: false,
    
    // 主题设置
    isDark: false,
    theme: 'light',
    primaryColor: '#115599',
    
    // 设备信息
    isMobile: false,
    isTablet: false,
    deviceType: 'desktop',
    
    // 侧边栏状态
    sidebarCollapsed: false,
    sidebarWidth: 240,
    
    // 语言设置
    language: 'zh-CN',
    
    // 面包屑导航
    breadcrumbs: [],
    
    // 标签页
    visitedViews: [],
    cachedViews: [],
    
    // 当前路由
    currentRoute: null,
    
    // 全屏状态
    isFullscreen: false,
    
    // 搜索状态
    searchVisible: false,
    
    // 帮助状态
    helpVisible: false,
    
    // 通知设置
    notifications: {
      enabled: true,
      sound: true,
      desktop: true,
      email: false
    },
    
    // 学习设置
    studySettings: {
      autoSave: true,
      autoSubmit: false,
      showTimer: true,
      showProgress: true,
      enableShortcuts: true,
      fontSize: 'medium',
      lineHeight: 'normal'
    },
    
    // 系统信息
    systemInfo: {
      version: '1.0.0',
      buildTime: '',
      environment: 'production'
    },
    
    // 网络状态
    networkStatus: 'online',
    
    // 操作历史
    operationHistory: [],
    
    // 快捷键映射
    shortcuts: {
      'ctrl+k': 'search',
      'ctrl+/': 'help',
      'f11': 'fullscreen',
      'esc': 'closeModal'
    }
  }),

  getters: {
    // 应用配置
    appConfig: (state) => ({
      theme: state.theme,
      language: state.language,
      primaryColor: state.primaryColor,
      sidebarCollapsed: state.sidebarCollapsed
    }),
    
    // 设备信息
    deviceInfo: (state) => ({
      isMobile: state.isMobile,
      isTablet: state.isTablet,
      deviceType: state.deviceType
    }),
    
    // 当前页面标题
    pageTitle: (state) => {
      return state.currentRoute?.meta?.title || '学生学习平台'
    },
    
    // 是否显示侧边栏
    showSidebar: (state) => {
      return !state.isMobile || !state.sidebarCollapsed
    },
    
    // 内容区域样式
    contentStyle: (state) => {
      const marginLeft = state.isMobile ? 0 : (state.sidebarCollapsed ? 64 : state.sidebarWidth)
      return {
        marginLeft: `${marginLeft}px`,
        transition: 'margin-left 0.3s ease'
      }
    },
    
    // 主题变量
    themeVars: (state) => {
      return {
        '--primary-color': state.primaryColor,
        '--sidebar-width': `${state.sidebarWidth}px`
      }
    }
  },

  actions: {
    // 初始化应用
    async initApp() {
      try {
        // 检测设备类型
        this.detectDevice()
        
        // 加载用户偏好设置
        this.loadUserPreferences()
        
        // 初始化主题
        this.initTheme()
        
        // 监听窗口变化
        this.setupWindowListeners()
        
        // 获取系统信息
        this.getSystemInfo()
        
        console.log('应用初始化完成')
      } catch (error) {
        console.error('应用初始化失败:', error)
        throw error
      }
    },

    // 设置加载状态
    setLoading(loading, text = '') {
      this.loading = loading
      this.loadingText = text
    },

    // 设置页面加载状态
    setPageLoading(loading) {
      this.pageLoading = loading
    },

    // 切换主题
    toggleTheme() {
      this.isDark = !this.isDark
      this.theme = this.isDark ? 'dark' : 'light'
      this.applyTheme()
      this.saveUserPreferences()
    },

    // 设置主题
    setTheme(theme) {
      this.theme = theme
      this.isDark = theme === 'dark'
      this.applyTheme()
      this.saveUserPreferences()
    },

    // 应用主题
    applyTheme() {
      const html = document.documentElement
      
      if (this.isDark) {
        html.classList.add('dark')
        html.setAttribute('data-theme', 'dark')
      } else {
        html.classList.remove('dark')
        html.setAttribute('data-theme', 'light')
      }
      
      // 设置主题色
      html.style.setProperty('--el-color-primary', this.primaryColor)
    },

    // 初始化主题
    initTheme() {
      // 检查系统主题偏好
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      
      if (this.theme === 'auto') {
        this.isDark = prefersDark
      }
      
      this.applyTheme()
      
      // 监听系统主题变化
      window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
        if (this.theme === 'auto') {
          this.isDark = e.matches
          this.applyTheme()
        }
      })
    },

    // 设置主题色
    setPrimaryColor(color) {
      this.primaryColor = color
      this.applyTheme()
      this.saveUserPreferences()
    },

    // 切换侧边栏
    toggleSidebar() {
      this.sidebarCollapsed = !this.sidebarCollapsed
      this.saveUserPreferences()
    },

    // 设置侧边栏状态
    setSidebarCollapsed(collapsed) {
      this.sidebarCollapsed = collapsed
      this.saveUserPreferences()
    },

    // 检测设备类型
    detectDevice() {
      const width = window.innerWidth
      
      if (width < 768) {
        this.isMobile = true
        this.isTablet = false
        this.deviceType = 'mobile'
        this.sidebarCollapsed = true
      } else if (width < 1024) {
        this.isMobile = false
        this.isTablet = true
        this.deviceType = 'tablet'
      } else {
        this.isMobile = false
        this.isTablet = false
        this.deviceType = 'desktop'
      }
    },

    // 设置语言
    setLanguage(language) {
      this.language = language
      this.saveUserPreferences()
      
      // 这里可以添加国际化逻辑
      ElMessage.success('语言设置已更新')
    },

    // 更新面包屑
    updateBreadcrumb(route) {
      const breadcrumbs = []
      
      // 添加首页
      breadcrumbs.push({
        title: '首页',
        path: '/dashboard'
      })
      
      // 解析路由路径
      const pathArray = route.path.split('/').filter(Boolean)
      let currentPath = ''
      
      pathArray.forEach((segment, index) => {
        currentPath += `/${segment}`
        
        // 查找匹配的路由
        const matchedRoute = route.matched.find(r => r.path === currentPath)
        if (matchedRoute && matchedRoute.meta?.title) {
          breadcrumbs.push({
            title: matchedRoute.meta.title,
            path: currentPath
          })
        }
      })
      
      this.breadcrumbs = breadcrumbs
    },

    // 添加访问过的视图
    addVisitedView(route) {
      if (route.meta?.hideInMenu) return
      
      const view = {
        name: route.name,
        path: route.path,
        title: route.meta?.title || route.name,
        fullPath: route.fullPath,
        query: route.query,
        params: route.params
      }
      
      const existingIndex = this.visitedViews.findIndex(v => v.path === view.path)
      
      if (existingIndex > -1) {
        // 更新现有视图
        this.visitedViews[existingIndex] = view
      } else {
        // 添加新视图
        this.visitedViews.push(view)
      }
      
      // 添加到缓存
      if (route.meta?.keepAlive && !this.cachedViews.includes(route.name)) {
        this.cachedViews.push(route.name)
      }
    },

    // 移除访问过的视图
    removeVisitedView(view) {
      const index = this.visitedViews.findIndex(v => v.path === view.path)
      if (index > -1) {
        this.visitedViews.splice(index, 1)
      }
      
      // 从缓存中移除
      const cacheIndex = this.cachedViews.indexOf(view.name)
      if (cacheIndex > -1) {
        this.cachedViews.splice(cacheIndex, 1)
      }
    },

    // 设置当前路由
    setCurrentRoute(route) {
      this.currentRoute = route
    },

    // 切换全屏
    toggleFullscreen() {
      if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen()
        this.isFullscreen = true
      } else {
        document.exitFullscreen()
        this.isFullscreen = false
      }
    },

    // 切换搜索
    toggleSearch() {
      this.searchVisible = !this.searchVisible
    },

    // 切换帮助
    toggleHelp() {
      this.helpVisible = !this.helpVisible
    },

    // 关闭所有模态框
    closeAllModals() {
      this.searchVisible = false
      this.helpVisible = false
    },

    // 更新通知设置
    updateNotifications(settings) {
      this.notifications = { ...this.notifications, ...settings }
      this.saveUserPreferences()
    },

    // 更新学习设置
    updateStudySettings(settings) {
      this.studySettings = { ...this.studySettings, ...settings }
      this.saveUserPreferences()
      
      // 应用字体大小设置
      this.applyFontSize()
    },

    // 应用字体大小
    applyFontSize() {
      const fontSizeMap = {
        small: '14px',
        medium: '16px',
        large: '18px',
        'extra-large': '20px'
      }
      
      const lineHeightMap = {
        tight: '1.25',
        normal: '1.5',
        relaxed: '1.75'
      }
      
      const html = document.documentElement
      html.style.setProperty('--app-font-size', fontSizeMap[this.studySettings.fontSize])
      html.style.setProperty('--app-line-height', lineHeightMap[this.studySettings.lineHeight])
    },

    // 添加操作历史
    addOperationHistory(operation) {
      this.operationHistory.unshift({
        ...operation,
        timestamp: new Date().toISOString()
      })
      
      // 只保留最近100条记录
      if (this.operationHistory.length > 100) {
        this.operationHistory = this.operationHistory.slice(0, 100)
      }
    },

    // 设置网络状态
    setNetworkStatus(status) {
      this.networkStatus = status
    },

    // 暂停操作
    pauseOperations() {
      // 暂停自动保存等操作
      console.log('暂停操作')
    },

    // 恢复操作
    resumeOperations() {
      // 恢复自动保存等操作
      console.log('恢复操作')
    },

    // 刷新数据
    async refreshData() {
      try {
        // 刷新应用数据
        console.log('刷新应用数据')
      } catch (error) {
        console.error('刷新数据失败:', error)
      }
    },

    // 获取系统信息
    getSystemInfo() {
      this.systemInfo = {
        version: import.meta.env.VITE_APP_VERSION || '1.0.0',
        buildTime: import.meta.env.VITE_BUILD_TIME || '',
        environment: import.meta.env.MODE
      }
    },

    // 设置窗口监听器
    setupWindowListeners() {
      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        this.detectDevice()
      })
      
      // 监听全屏变化
      document.addEventListener('fullscreenchange', () => {
        this.isFullscreen = !!document.fullscreenElement
      })
      
      // 监听网络状态变化
      window.addEventListener('online', () => {
        this.setNetworkStatus('online')
      })
      
      window.addEventListener('offline', () => {
        this.setNetworkStatus('offline')
      })
    },

    // 加载用户偏好设置
    loadUserPreferences() {
      try {
        const preferences = localStorage.getItem('appPreferences')
        if (preferences) {
          const parsed = JSON.parse(preferences)
          
          this.theme = parsed.theme || this.theme
          this.isDark = parsed.isDark ?? this.isDark
          this.primaryColor = parsed.primaryColor || this.primaryColor
          this.sidebarCollapsed = parsed.sidebarCollapsed ?? this.sidebarCollapsed
          this.language = parsed.language || this.language
          this.notifications = { ...this.notifications, ...parsed.notifications }
          this.studySettings = { ...this.studySettings, ...parsed.studySettings }
        }
      } catch (error) {
        console.error('加载用户偏好设置失败:', error)
      }
    },

    // 保存用户偏好设置
    saveUserPreferences() {
      try {
        const preferences = {
          theme: this.theme,
          isDark: this.isDark,
          primaryColor: this.primaryColor,
          sidebarCollapsed: this.sidebarCollapsed,
          language: this.language,
          notifications: this.notifications,
          studySettings: this.studySettings
        }
        
        localStorage.setItem('appPreferences', JSON.stringify(preferences))
      } catch (error) {
        console.error('保存用户偏好设置失败:', error)
      }
    }
  },

  // 持久化配置
  persist: {
    key: 'student-app-store',
    storage: localStorage,
    paths: ['theme', 'isDark', 'primaryColor', 'sidebarCollapsed', 'language', 'notifications', 'studySettings']
  }
})